package com.time.config;

import com.time.filter.JwtAuthenticationTokenFilter;
import com.time.service.impl.AccessDeniedHandlerImpl;
import com.time.service.impl.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author mjw
 * @date 2022/11/22
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                //不通过Session获取SecurityContext
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口，允许匿名访问
                .antMatchers("/hello").hasAnyAuthority("admin", "user")
                .antMatchers("/admin/**").hasAuthority("admin")
                .antMatchers("/user/login").anonymous()
                // 除上面以外的全部接口 都需要权限验证
                .anyRequest()
                .authenticated()
                .and()
                // 关闭csrf
                .csrf()
                .disable();
        // 处理异常
        httpSecurity
                .exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPointImpl())
                .accessDeniedHandler(new AccessDeniedHandlerImpl());

        //把token校验过滤器添加到过滤器链中
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }

    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
        return authenticationManager;
    }

    /*
    @Bean
    public SecurityFilterChain config(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasAnyRole("admin", "user")
                .antMatchers("/visitor/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .permitAll()
                // 配置成功处理器
                .successHandler(new SecurityAuthenticationSuccessHandler())
                // 配置失败处理器
                .failureHandler(new SecurityAuthenticationFailureHandler())
                .and()
                // 退出登录
                .logout()
                .logoutSuccessHandler(new SecurityLogoutSuccessHandler())
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                // 未登录时的处理器
                .authenticationEntryPoint(new SecurityAuthenticationEntryPoint())
                .and()
                .httpBasic();
        return httpSecurity.build();
    }

     */

//    @Autowired
//    private UserDetailsService userDetailsService;
//
//    @Bean
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        //关联UserDetailsService对象
//        auth.userDetailsService(userDetailsService)
//                //暂时不对密码进行加密配置
//                .passwordEncoder(NoOpPasswordEncoder.getInstance());
//    }
    /*
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user1 = User.withUsername("user")
                .passwordEncoder(new Pbkdf2PasswordEncoder()::encode)
                .password("123")
                .roles("user")
                .build();
        UserDetails user2 = User.withUsername("admin")
                .passwordEncoder(new Pbkdf2PasswordEncoder()::encode)
                .password("123")
                .roles("admin", "user")
                .build();
        UserDetails user3 = User.withUsername("time")
                .passwordEncoder(new Pbkdf2PasswordEncoder()::encode)
                .password("1234")
                .roles("admin")
                .build();
        return new InMemoryUserDetailsManager(user1, user2, user3);
    }

     */

    /*
    推荐使用 Pbkdf2PasswordEncoder 加密器，该加密器可以在创建时可以传入一个字符串阴钥，从而获得一个只属于你的加密器，即使数据库中密码的加密字符串被盗取，如果没有阴钥，则永远无法获得原密码

而对于 BCryptPasswordEncoder ，被盗取加密字符串后，如果用户使用了简单密码，则可以通过彩虹表获取原密码
    */

    /*
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new Pbkdf2PasswordEncoder();
    }

     */

//    @Bean
//    public SecurityFilterChain config(HttpSecurity httpSecurity) throws Exception {
//        httpSecurity.authorizeRequests()
//                // 对任意请求都认证
//                .anyRequest()
//                .authenticated()
//                .and()
//                // 开启basic认证
//                .httpBasic();
//        return httpSecurity.build();
//    }

    // 新配置
//    @Bean
//    public SecurityFilterChain config(HttpSecurity httpSecurity) throws Exception {
//        httpSecurity.authorizeRequests()
//                // 对任意请求都认证
//                .anyRequest()
//                .authenticated()
//                .and()
//                // 开启form认证
//                .formLogin()
//                // 加载自定义的登录页面地址
//                .loginPage("/user-login")
//                .loginProcessingUrl("/login")
//                .permitAll()
//                .and()
//                //注意:需禁用csrf防护功能,否则登录不成功
//                .csrf()
//                .disable();
//        return httpSecurity.build();
//    }
}
